package com.cocotingo.snail.template;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

import com.cocotingo.snail.template.models.Node;
import com.cocotingo.snail.template.models.TemplateDefinitionsNode;

public class XMLTemplateWritter {
	
	public static String escapeXMLCharacters(String str) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < str.length(); i++) {
			char ch = str.charAt(i);
			if (ch == '<') {
				buf.append("&lt;");
			} else if (ch == '>') {
				buf.append("&gt;");
			} else if (ch == '&') {
				buf.append("&amp;");
			} else if (ch == '\'') {
				buf.append("&apos;");
			} else if (ch == '\"') {
				buf.append("&quot;");
			} else {
				buf.append(ch);
			}
		}
		if (buf.length() == str.length()) {
			return str;
		} else {
			return buf.toString();
		}
	}
	
	public XMLTemplateWritter() {
	}
	
	public void write(TemplateDefinitionsNode node, OutputStream stream) throws IOException {
		try {
			Writer writer = new BufferedWriter(new OutputStreamWriter(stream, "UTF-8"));
			writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
			writer.write("<!-- Snail GUI Template File -->\n");
			write(node, writer, 0);
			writer.flush();
		} catch (UnsupportedEncodingException e) {
			throw new TemplateRuntimeException(e);
		}
	}
	
	private void write(Node node, Writer writer, int tab) throws IOException {
		for (int i = 0; i < tab; i++) writer.write('\t');
		writer.write(node.getXMLStartTag());
		writer.write('\n');
		for (Node child : node.children()) {
			write(child, writer, tab + 1);
		}
		for (int i = 0; i < tab; i++) writer.write('\t');
		writer.write(node.getXMLEndTag());
		writer.write('\n');
	}
	
	

}
